package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.app.Dialog;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.king.image.imageviewer.ImageViewer;
import com.king.image.imageviewer.loader.GlideImageLoader;
import com.vilyever.drawingview.DrawingView;
import com.vilyever.drawingview.brush.drawing.PenBrush;
import com.vilyever.drawingview.brush.drawing.PolygonBrush;
import com.vilyever.drawingview.brush.drawing.ShapeBrush;

import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.ColorAdapter;
import flc.ast.bean.FrameBean;
import flc.ast.databinding.ActivityDrawBinding;
import flc.ast.dialog.ColorDialog;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.utils.FastClickUtil;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.RxUtil;

public class DrawActivity extends BaseAc<ActivityDrawBinding> {

    public static int type;//0开始作画 1披萨画册
    public static Integer img;
    private String mSelectColor;
    private PenBrush mPenBrush;
    private ColorAdapter colorAdapter;
    private Dialog myImageDialog;


    @Override
    protected int onCreate() {
        return R.layout.activity_draw;
    }

    @Override
    protected void initView() {
        mDataBinding.ivDrawBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.ivDrawSave.setOnClickListener(this);
        mDataBinding.flDrawSelectColor.setOnClickListener(this);
        mDataBinding.ivDrawDraw.setOnClickListener(this);
        mDataBinding.ivDrawEraser.setOnClickListener(this);
        mDataBinding.ivDrawRevocation.setOnClickListener(this);
        mDataBinding.ivDrawRecover.setOnClickListener(this);
        mDataBinding.rsbBrightness.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                mPenBrush.setSize(progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        mPenBrush = PenBrush.defaultBrush();
        mDataBinding.drawingView.setBrush(mPenBrush);
        mDataBinding.drawingView.setUndoRedoStateDelegate(new DrawingView.UndoRedoStateDelegate() {
            @Override
            public void onUndoRedoStateChange(DrawingView drawingView, boolean canUndo, boolean canRedo) {
                if (canUndo) {
                    mDataBinding.ivDrawRevocation.setImageResource(R.drawable.axiangqianchehu);
                } else {
                    mDataBinding.ivDrawRevocation.setImageResource(R.drawable.axiangqianchehu1);
                }
                if (canRedo) {
                    mDataBinding.ivDrawRecover.setImageResource(R.drawable.axhch1);
                } else {
                    mDataBinding.ivDrawRecover.setImageResource(R.drawable.axhch);
                }
            }
        });
        mDataBinding.rvColorList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        colorAdapter = new ColorAdapter();
        mDataBinding.rvColorList.setAdapter(colorAdapter);
        colorAdapter.setOnItemClickListener(this);
//        mDataBinding.moveImageView.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                ImageViewer.load(img)//要加载的图片数据，单张或多张
//                        .selection(0)//当前选中位置，默认：0
//                        .indicator(false)//是否显示指示器，默认不显示
//                        .imageLoader(new GlideImageLoader())//加载器，imageLoader必须配置，目前内置的有GlideImageLoader或PicassoImageLoader，也可以自己实现
//                        .theme(R.style.ImageViewerTheme)//设置主题风格，默认：R.style.ImageViewerTheme
//                        .orientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)//设置屏幕方向,默认：ActivityInfo.SCREEN_ORIENTATION_BEHIND
//                        .start(DrawActivity.this);//activity or fragment, 跳转时的共享元素视图
//            }
//        });
        mDataBinding.moveImageView.setOnClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        if (FastClickUtil.isFastClick()) return;
        switch (v.getId()) {
            case R.id.flDrawSelectColor:  // 选择颜色
                ColorDialog colorDialog = new ColorDialog(mContext);
                colorDialog.setListener(new ColorDialog.IListener() {
                    @Override
                    public void onClickConfirm(String color) {
                        mSelectColor = color;
                        mPenBrush.setColor(Color.parseColor(mSelectColor));
                        mDataBinding.crlColorBg.setColor(Color.parseColor(mSelectColor));
                    }
                });
                colorDialog.show();
                break;
            case R.id.ivDrawDraw:  // 画笔
                initControl();
                mDataBinding.ivDrawDraw.setImageResource(R.drawable.ahuabi);
                break;
            case R.id.ivDrawEraser:  // 橡皮檫
                initControl();
                mDataBinding.ivDrawEraser.setImageResource(R.drawable.axiangpicada);
                mPenBrush.setIsEraser(true);
                break;
            case R.id.ivDrawRecover:  // 复原
                mDataBinding.drawingView.redo();
                break;
            case R.id.ivDrawRevocation:  // 撤回
                mDataBinding.drawingView.undo();
                break;
            case R.id.ivDrawSave:
                save();
                break;
            case R.id.moveImageView:
                myImageDialog.show();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        colorAdapter.getItem(0).setSelected(false);
        colorAdapter.notifyItemChanged(0);
        colorAdapter.getItem(position).setSelected(true);
        colorAdapter.notifyItemChanged(position);
        mPenBrush.setColor(Color.parseColor(colorAdapter.getItem(position).getFrameColor()));
        FrameBean bean=colorAdapter.getItem(position);
        colorAdapter.remove(bean);
        colorAdapter.addData(0,bean);
        colorAdapter.notifyDataSetChanged();
    }

    @Override
    protected void initData() {
        if (type==0){
            mDataBinding.moveImageView.setVisibility(View.GONE);
        }else {
            Glide.with(mContext).load(img)
                    .transform(new RoundedCorners(20))
                    .into(mDataBinding.moveImageView);
//            mDataBinding.moveImageView.setImageResource(img);
            //图片弹框
            imageDialog();
            mDataBinding.moveImageView.setVisibility(View.VISIBLE);
        }
        List<FrameBean> mFrameBeanList = new ArrayList<>();
        mFrameBeanList.add(new FrameBean("#FFFFFF"));
        mFrameBeanList.add(new FrameBean("#000000"));
        mFrameBeanList.add(new FrameBean("#FFDF8D"));
        mFrameBeanList.add(new FrameBean("#3A52BD"));
        mFrameBeanList.add(new FrameBean("#9BA9DE"));
        mFrameBeanList.add(new FrameBean("#00B8AB"));
        mFrameBeanList.add(new FrameBean("#63CDC3"));
        mFrameBeanList.add(new FrameBean("#CDA163"));
        mFrameBeanList.add(new FrameBean("#FF6159"));
        mFrameBeanList.add(new FrameBean("#FF5592"));
        mFrameBeanList.add(new FrameBean("#D990DE"));
        mFrameBeanList.add(new FrameBean("#8455C7"));
        mFrameBeanList.add(new FrameBean("#4C78FF"));
        mFrameBeanList.add(new FrameBean("#00E9FF"));
        mFrameBeanList.add(new FrameBean("#BEE29E"));
        mFrameBeanList.add(new FrameBean("#9AFFDA"));
        mFrameBeanList.get(0).setSelected(true);
        colorAdapter.setList(mFrameBeanList);
    }

    private void save() {
        showDialog(getString(R.string.save_ing));
        RxUtil.create(new RxUtil.Callback<Boolean>() {
            @Override
            public void doBackground(ObservableEmitter<Boolean> emitter) {
                String audioOutPath = FileUtil.generateFilePath(Content.myDraw, ".png");
                boolean save = ImageUtils.save(ImageUtils.view2Bitmap(mDataBinding.drawingView), audioOutPath, Bitmap.CompressFormat.PNG);
                emitter.onNext(save);
            }

            @Override
            public void accept(Boolean obj) {
                dismissDialog();
                ToastUtils.showShort(R.string.save_suc);
            }
        });
    }

    private void initControl() {
        mDataBinding.ivDrawDraw.setImageResource(R.drawable.ahuabixiao);
        mDataBinding.ivDrawEraser.setImageResource(R.drawable.axiangpica);
        mPenBrush.setIsEraser(false);
    }

    //图片弹框
    private void imageDialog() {
        myImageDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_img, null);
        myImageDialog.setContentView(inflate);
        myImageDialog.setCancelable(true);
        Window dialogWindow = myImageDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.9);
        lp.y = 50;
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        ImageView imageView=inflate.findViewById(R.id.ivDialogImg);
        imageView.setImageResource(img);
    }

}